﻿using System;
using System.Web.Mvc;
using Pay.Core;
using Pay.TO;
namespace Pay.Token {
    /// <summary>
    /// 错误日志
    /// </summary>
    public class HandleExceptionAttribute : HandleErrorAttribute, IExceptionFilter {
		public override void OnException(ExceptionContext filterContext) {
			if (filterContext == null)
				throw new ArgumentNullException("filterContext");
			if (filterContext.IsChildAction)
				return;
			if (filterContext.ExceptionHandled)
				return;
			var ex = filterContext.Exception.GetBaseException() ?? new Exception("No further infomation exists.");
			if (!ExceptionType.IsInstanceOfType(ex))
				return;

			var log = IocHelper.Get<ILogHelper>("ui_error");
            if (!(ex is ServerErrorException || ex is DataErrorException || filterContext.HttpContext.Response.StatusCode == 401))
				log.Error(ex.Message, ex);
			if (filterContext.HttpContext.Request.IsAjaxRequest()) {
                if (ex is ServerErrorException) {
                    var serverEx = ex as ServerErrorException;
                    if (serverEx.ErrorCode > 0)
                        filterContext.Result = new JsonNetResult(new ResultMessage<object>(serverEx.ErrorCode, ex.Message));
                    else
                        filterContext.Result = new JsonNetResult(new ResultMessage<object>(filterContext.HttpContext.Response.StatusCode, ex.Message));
                } else {
#if DEBUG
                    filterContext.Result = new JsonNetResult(new ResultMessage<object>(filterContext.HttpContext.Response.StatusCode, ex.Message));
#else
                    filterContext.Result = new JsonNetResult(new ResultMessage<object>(filterContext.HttpContext.Response.StatusCode, "网络异常，请稍后再试"));
#endif
                }
            } else {
				HandleErrorInfo data = new HandleErrorInfo(ex, (string)filterContext.RouteData.Values["controller"], (string)filterContext.RouteData.Values["action"]);
				filterContext.Controller.ViewData.Model = data;
				filterContext.Result = new ViewResult { ViewName = "Error", ViewData = filterContext.Controller.ViewData };
			}
			filterContext.ExceptionHandled = true;
			filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
		}
	}
}
